package com.wyz.calibur.infrastructure.config.security;

import com.alibaba.fastjson.JSON;
import com.wyz.calibur.constant.SecurityConstant;
import com.wyz.calibur.enums.ResultCode;
import com.wyz.calibur.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 认证异常
 * @Author: wei yz
 * @Date: 2022/6/20 15:35
 */
public class CliburAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(CliburAuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String message = null;
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            message = "用户名或密码输入错误，登录失败!";
        } else if (e instanceof DisabledException) {
            message = "账户被禁用，登录失败，请联系管理员!";
        } else if (e instanceof InternalAuthenticationServiceException) {
            message = "token失效或不存在！";
        } else if (e instanceof InsufficientAuthenticationException) {
            log.error("==> 权限决策管理器抛出的异常信息：{}, {}", e.getMessage(), e.getLocalizedMessage());
            message = "权限不足或token异常,无法访问系统资源";
            if (e.getMessage().equals(String.valueOf(ResultCode.UNAUTHORIZED.getCode()))) {
                message = "登录凭证Token失效";
            }
            if (e.getMessage().equals(String.valueOf(ResultCode.PARAMETER_ERROR.getCode()))) {
                message = "登录凭证Token为空";
            }
            log.error("==> 组装后的信息 [{}], 抛出的信息：{}", message, e.getMessage());
        } else {
            message = e.getMessage();
            log.error("==> 认证异常信息：{}", e.getMessage());
        }
        log.error("==> 【自定义】捕获异常信息：{}", message);
        response.setContentType(SecurityConstant.CONTENT_TYPE);
        response.getWriter().println(
                JSON.toJSONString(new Result()
                        .setSuccess(false)
                        .setCode(ResultCode.UNAUTHORIZED)
                        .setMessage(message)));

    }
}
